package com.zeng.createmd.restfulmodule.util;

import com.zeng.createmd.servicemodule.vo.DatabaseVo;
import com.zeng.plugin.util.FreeMarkUtil;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

public class PropertyUtil {

    public static void createDbProperty(DatabaseVo databaseVo, File target) {
        FreeMarkUtil freeMarkUtil = new FreeMarkUtil(db, null);
        Map<String,Object> data = new HashMap<>();
        data.put("username", databaseVo.getAccount());
        data.put("password", databaseVo.getPassword());
        data.put("url", databaseVo.getAddress() + ":" + databaseVo.getPort());
        data.put("database", databaseVo.getName());
        String parse = freeMarkUtil.parse(data);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(target);
            IOUtils.write(parse, fileOutputStream, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            CloseUtil.close(fileOutputStream);
        }
    }
    private static String db = "spring.datasource.username=${username}\n" +
            "spring.datasource.password=${password}\n" +
            "spring.datasource.url=jdbc:mysql://${url}/${database}?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false";
}


